<!--
 * @Author: ssj
 * @Date: 2021-07-24 09:17:27
 * @LastEditors: swc
 * @LastEditTime: 2025-02-21 13:08:21
 * @Description: 
-->

<template>
  <o-modal
    v-model="isShow"
    :title="$srv.getI18nByPath('vxe.import.impConfirm')"
    :size="config.modalSize || [385, 335]"
    :mask="true"
    :tap-close="false"
    :show-footer="true"
    @on-close="modalClose"
  >
    <div slot="content" class="modalbox clear">
      <div class="import-panel">
        <div class="options" v-show="false">
          <Form :model="formItem" label-colon>
            <FormItem :label="$srv.getI18nByValue('处理')">
              <RadioGroup v-model="formItem.dataHandle">
                <Radio label="insert">{{ $srv.getI18nByValue('插入') }}</Radio>
                <Radio label="update">{{ $srv.getI18nByValue('更新') }}</Radio>
              </RadioGroup>
            </FormItem>
            <FormItem :label="$srv.getI18nByValue('选项')">
              <RadioGroup v-model="formItem.option">
                <Radio label="import">{{
                  $srv.getI18nByValue('同步写表')
                }}</Radio>
                <Radio label="uploadOnly">{{
                  $srv.getI18nByValue('只上传文件')
                }}</Radio>
              </RadioGroup>
            </FormItem>
            <FormItem :label="$srv.getI18nByValue('模式')">
              <RadioGroup v-model="formItem.mode">
                <Radio label="strict">{{ $srv.getI18nByValue('严格') }}</Radio>
                <Radio label="match">{{ $srv.getI18nByValue('匹配') }}</Radio>
              </RadioGroup>
            </FormItem>
          </Form>
        </div>
        <Divider v-show="false" />
        <div class="import-toolbar">
          <Upload
            :action="$srv.url.upload"
            :data="importUploadParams"
            :multiple="false"
            ref="upload"
            name="files"
            accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            :max-size="20480"
            :before-upload="importBeforeUpload"
            :on-progress="importUploadOnProgress"
            :on-success="importUploadOnSuccess"
            :on-error="importUploadOnError"
            :on-remove="importUploadOnRemove"
            :on-format-error="importUploadOnFormatError"
            :on-exceeded-size="importUploadOnExceedSize"
            :disabled="disableList.upload"
          >
            <Button
              class="toolbar-btn select no-border"
              icon="ios-cloud-upload-outline"
              type="primary"
            >
              <!-- 选择 -->
              {{ $srv.getI18nByPath('others.choose') }}
              Excel
            </Button>
          </Upload>
          <span class="upload-speed">{{ speed }}</span>
        </div>
      </div>
    </div>
  </o-modal>
</template>

<script lang="ts">
import oModal from '@/components/base/modal/o-modal/index.vue';
import { Tsrv, T_srv, ifs, ts, vue } from '@/services';

interface I_params {
  funInfo: {
    funName: string;
    fileName: string;
  };
  lang: string;
  type: string;
  dataHandle: 'insert' | 'update';
  option: 'import' | 'uploadOnly';
  mode: 'strict' | 'match';
}

interface config {
  funName: string;
  modalSize?: Array<number>;
}

@T_srv.comp({
  components: {
    oModal
  }
})
export default class oImportPanel extends vue {
  @T_srv.prop() config: config;

  @T_srv.prop() id: string;

  @T_srv.ref() readonly tempTable!: any;

  private isShow: boolean = false;

  private tempTableName: string = '';

  private importTempTableConfig = null;

  public formItem = {
    dataHandle: 'insert',
    option: 'import',
    mode: 'strict'
  };

  public importUploadParams = {
    dbName: Tsrv.getDBName(),
    params: null
  };

  private importSettingTableConfig = null;

  private isSettingOpen = false;

  private importSettingID = null;

  private importSettingName = '';

  private tempTableColumns = [];

  private lastLoadTime: number = 0;

  private lastLoaded: number = 0;

  private speed: string = '';

  private disableList = {
    upload: false,
    setting: true,
    check: true
  };

  private funName: string = '';

  private importing: any = null;

  created() {
    this.init();
  }

  mounted() {
    // this.init();
  }

  public init() {
    this.funName = this.config.funName;
    this.tempTableName = '';
    this.importTempTableConfig = null;

    this.importSettingTableConfig = null;

    this.isSettingOpen = false;
    this.importSettingID = null;
    this.importSettingName = '';
    this.tempTableColumns = [];

    this.lastLoadTime = 0;
    this.lastLoaded = 0;
    this.speed = '';

    this.disableList = {
      upload: false,
      setting: true,
      check: true
    };
    this.show();
  }

  public show() {
    this.isShow = true;
  }

  public hide() {
    this.isShow = false;
  }

  public modalClose() {
    this.hide();
    this.$bus.$emit(`modal_${this.id}`, this.id);
  }

  private importCheck() {
    if (this.importSettingID !== null) {
      const params = {
        pFuncName: this.funName,
        pTmpTableName: this.tempTableName,
        pModalID: this.importSettingID
      };
      const msg = this.$Message.loading({
        // content: "文件检查中...",
        content: `${Tsrv.getI18nByPath('oimportpanel.filechecking')}···`,
        duration: 0
      });
      const startTime = new Date().getTime();
    }
  }

  private getColumnStyle() {
    if (this.importSettingID !== null && this.tempTableName !== '') {
      const params = {
        partName: `t_ItemInPutFormat`,
        pageNo: 1,
        pageSize: 100,
        filter: `FInputID=${this.importSettingID}`,
        sort: ''
      };
    }
  }

  private importBeforeUpload(file) {
    this.disableList.upload = true;
    if (this.funName) {
      // 只传一次
      const obj = {
        funInfo: [{ funName: this.funName, fileName: file.name }],
        lang: this.$i18n.locale || Tsrv.globalVar.i18n.enUS,
        type: 'import',
        dataHandle: this.formItem.dataHandle,
        option: this.formItem.option,
        mode: this.formItem.mode
      };
      this.importUploadParams.params = JSON.stringify(obj);
      this.importUploadParams.dbName = Tsrv.getDBName();
      this.lastLoadTime = new Date().getTime();
      this.lastLoaded = 0;
      return true;
    }
    return false;
  }

  private importUploadOnProgress(e) {
    const diffTime = (new Date().getTime() - this.lastLoadTime) / 1000;
    const diffLoaded = (e.loaded - this.lastLoaded) / 1000;
    const speed = Tsrv.utils.toFixedDecimal(diffLoaded / diffTime, 0);
    Tsrv.utils.tofix;
    let speedStr = '';
    if (speed < 1000) {
      speedStr = `${speed}Kb/s`;
    } else {
      speedStr = `${Tsrv.utils.toFixedDecimal(speed / 1000, 1)}Mb/s`;
    }
    this.lastLoadTime = new Date().getTime();
    this.lastLoaded = e.loaded;
    this.speed = speedStr;
    this.startImportMsg();
  }

  private startImportMsg() {
    this.importing = this.$Message.loading({
      content: `${Tsrv.getI18nByValue('正在导入')}···`,
      duration: 0
    });
  }

  private closeImportMsg() {
    if (this.importing !== null) {
      this.importing();
      this.importing = null;
    }
  }

  private importUploadOnSuccess(response) {
    this.closeImportMsg();
    this.speed = '';
    this.$msg(response.msg);
    if (response.success) {
      this.modalClose();
    }
    if (
      Array.isArray(response?.data?.report) &&
      response.data.report.length > 0
    ) {
      response.data.report.forEach(fName => {
        const dwn = new ts.T_downloadArg();
        dwn.setPath('temp').setFileName(fName);
        Tsrv.download(dwn, true)
          .then(r => {
            if (r.err) {
              console.error(Tsrv.getI18nByValue('下载文件错误'));
            }
          })
          .catch(err => {
            console.error(Tsrv.getI18nByValue('下载文件错误'));
          });
      });
    }
  }

  private importUploadOnError(error) {
    this.closeImportMsg();
    this.$msg(error);
  }

  private importUploadOnRemove() {
    this.disableList.upload = false;
    this.disableList.setting = true;
    this.disableList.check = true;
  }

  private importUploadOnFormatError() {}

  private importUploadOnExceedSize() {}

  private openSetting() {
    Tsrv.utils
      .createModal('oMagicBox', {
        source: { funid: null, field: 't_ItemInPut', limit: 1 },
        config: {
          isFunLayout: true
        }
      })
      .then(data => {
        if (data && data.length > 0) {
          this.importSettingID = data[0].id;
          this.importSettingName = `(${data[0].FCaption})`;
          this.getColumnStyle();
          this.disableList.check = false;
        }
      });
  }
}
</script>

<style lang="scss" scoped>
.modalbox {
  padding: 0 20px;
  height: 100%;
  .setting-modal ::v-deep {
    .setting-panel {
      height: 100%;
    }
  }
  .import-panel {
    width: 100%;
    height: 100%;
    .options {
      padding: 6px;
      .ivu-form-item {
        margin-bottom: 8px;
      }
    }

    .import-toolbar ::v-deep {
      .ivu-upload {
        float: left;
        display: flex;
        align-items: center;
        .ivu-upload-list {
          margin: 0 10px;
        }
      }
    }
    .import-toolbar {
      width: 100%;
      height: 50px;
      padding: 0px 6px;
      overflow: hidden;
      .upload-speed {
        line-height: 32px;
        color: #999;
        float: left;
      }
      > .toolbar-btn {
        float: right;
        margin-left: 20px;
      }
    }

    .import-grid {
      height: calc(100% - 50px);
      width: calc(100% - 40px);
      margin: 0 20px;
    }
  }
}
</style>
